package nl.tue.be.ds.duraark.bSDD.dump;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.ws.rs.core.MediaType;

import nl.tue.be.ds.duraark.bSDD.ClientUtilities;
import nl.tue.be.ds.duraark.bSDD.DataBaseUtilities;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;


public class ConSearchPerTermCallable implements Callable<Integer> {
	
	private String searchTerm;
	private final String searchByTermUrl = "http://bsddpilot.catenda.no/api/4.0/IfdConcept/search/";
	
	
	public ConSearchPerTermCallable(String searchTerm) {
		this.searchTerm = searchTerm;
	}

	public Integer call() throws Exception {
		
		Integer conceptCounter = new Integer(dumpPerTerm(searchPerTerm()));
		DataBaseUtilities.db.commit();
		return conceptCounter;
	}
	
/*	private Integer dumpPerTerm(JsonNode jsonConcepts){
		Integer i = 1;
		
		DumpProcessor.jsonConceptsList.add(jsonConcepts);
		//DumpProcessor.processDumpBySearchCallable();
		
		return i;
	}*/
	
	private Integer dumpPerTerm(JsonNode jsonConcepts){
		Integer i = 0;
		
		StorageUnitDumpCallable dsu = new StorageUnitDumpCallable(jsonConcepts);		
		ExecutorService threadPool = Executors.newSingleThreadExecutor();
		Future<Integer> f = threadPool.submit(dsu);
		
		try {
				i = f.get();
		} catch (InterruptedException e) {
			
			e.printStackTrace();
		} catch (ExecutionException e) {
			
			e.printStackTrace();
		}
		
		threadPool.shutdown(); 
		
		return i;
		
	}
	
	
	private JsonNode searchPerTerm() throws Exception{
		String res = null;
		JsonNode jsonConcepts;
		Client client = ClientUtilities.getClient();

		WebResource searchCall = client.resource(searchByTermUrl + searchTerm);
		
		res = getSearch(searchCall,0);
	
		if (res != null) {
			ObjectMapper mapper = ClientUtilities.getMapper();
			JsonNode root = mapper.readTree(res);
			jsonConcepts = root.get("IfdConcept");
		} else {
			jsonConcepts = null;
		}
		return jsonConcepts;
		
	}
	
	private String getSearch(WebResource searchCall, int searchRound) throws Exception{
		String res = null;
		if (searchRound < 10){
			try{
				res = searchCall.accept(MediaType.APPLICATION_JSON_TYPE).cookie(ClientUtilities.cookie).get(String.class);
			}catch(Exception e){
				if (e instanceof UniformInterfaceException){
					res = getSearch(searchCall, searchRound+1);
				}else{
					e.printStackTrace();
				}
			}
		}else{
			throw new Exception("Concepts for search term : " + searchTerm + " overflow");
		}
		
		return res;
		
	}

	
}
